<template>
  <div>
    <!-- 搜索框 -->
    <TopFilter :list="topFilterList" :cols="3" :labelWidth="'120'" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <ButtonArea :style="{ paddingLeft: '0px' }">
      <el-button size="small" type="primary" icon="el-icon-download" :loading="exportLoading" @click="exportData()">导出</el-button>
    </ButtonArea>

    <!-- 车主生日提醒列表 -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :selectionType="'single'"
      columnsRef="KhghczsrtxTable"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.choose = columns)"
    >
    </FilterTable>

    <!-- 提醒录入 -->
    <Drawer :visible.sync="showRemind" title="提醒录入" width="800" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <RemindInputs ref="RemindInputs" :type="handleType" :remindData="selectData" :remindSource="4" @close="cancle(1)" />
    </Drawer>

    <!-- 提醒历史 -->
    <Drawer :visible.sync="showRemindRecord" title="提醒历史" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <remindHistory :vin="chooseVin" :ownerNo="chooseOwnerNo" :remindSource="4"></remindHistory>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9999,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }"
      >
        <el-button @click="cancle(2)">返 回</el-button>
      </div>
    </Drawer>

    <!-- 预约安排 -->
    <Drawer :visible.sync="showReservation" title="预约安排" width="1350" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Precontract ref="Precontract" :Vin="chooseVin" :License="chooseLicense" @close="cancle(3)" />
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9999,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }"
      >
        <el-button @click="cancle(3)">返 回</el-button>
      </div>
    </Drawer>

    <!-- 维修历史 -->
    <Drawer :visible.sync="showRepairHistory" title="维修历史" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <repairHistory ref="repairHistory" :getdata="repairHistoryData" @close="cancle(4)" />
    </Drawer>

    <!-- 维修建议 -->
    <Drawer :visible.sync="showRepairSuggest" title="维修建议" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <!-- <RepairImport ref="RepairImport" :vin="chooseVin" @cancel="cancle(5)" /> -->
    </Drawer>

    <!-- 投诉历史 -->
    <Drawer :visible.sync="showComplaintHistory" title="投诉历史" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <complaintHistory ref="complaintHistory" :vin="chooseVin" @close="cancle(6)"></complaintHistory>
    </Drawer>
  </div>
</template>
<script>
import _ from 'lodash';
import moment from 'moment';
import dictCode from '@/utils/dictCode';
import { jsonToHump } from '@/utils/index';
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
// import { queryUnBirthdayRemind, exportCompaintHandling } from '@/api/customerRepair/customerCare/birthdayRemind';

import { getLostRuleInfo, getSwingRemindList, LSexport1, LSexport2, LSexport3 } from '@/api/customerRepair/customerLoss/lossRemind';

import { getPinpSelect } from '@/api/customerRepair/customerCare/maintenanceRemind/index';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import RemindInputs from '@/pages/customerRepair/customerLoss/lossRemind/remindCare/lostRemindEdit.vue';
import RemindHistory from '@/pages/customerRepair/customerCare/vehicleRemind/components/remindHistory.vue';
import repairHistory from '@/pages/repair/business/customer/Repairhistory/historypop.vue';
import Precontract from '@/pages/repair/repairReception/precontractArrange';
import complaintHistory from '@/pages/repair/business/customer/combination/complaint';
// import RepairImport from '@/pages/repair/repairReception/customer/repairImport/Modal.vue';
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import { getBrand, getSeries, getModel, getRegion } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';

export default {
  name: 'lostWarningRemind',
  components: {
    RemindInputs,
    RemindHistory,
    repairHistory,
    // RepairImport,
    complaintHistory,
    Precontract
  },
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createTopFilterList(), // 搜索列
      fetchApi: getSwingRemindList, // 获取车主生日接口
      fetchParams: { xhrAbort: true }, // 获取车主生日列表表格参数
      columns: this.createTableColumns(), // 车主生日表格列
      exportLoading: false, // 导出加载中
      choose: [], // 选中数据
      showRemind: false, // 提醒录入
      showRemindRecord: false, // 提醒历史
      showReservation: false, // 预约安排
      showRepairHistory: false, // 维修历史
      showRepairSuggest: false, // 建议维修
      showComplaintHistory: false, // 投诉历史
      chooseVin: null, // 选中的vin
      chooseLicense: null, // 选中的license
      chooseOwnerNo: null, // 选中的数据的ownerNo
      repairHistoryData: {}, // 维修历史数据
      selectData: null,
      handleType: '',
      lostRuleData: ''
    };
  },
  created() {},
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;

    this.getLostRuleInfo();
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '预警下限天数',
          fieldName: 'MIN_LIMIT',
          hidden: true,
          disabled: true
        },
        {
          type: 'INPUT',
          label: '预警摇摆天数',
          fieldName: 'LOSS_LIMIT',
          disabled: true,
          hidden: true
        },
        {
          type: 'INPUT',
          label: '预警上限天数',
          fieldName: 'MAX_LIMIT',
          disabled: true,
          hidden: true
        },
        {
          type: 'INPUT',
          label: '车主名称',
          fieldName: 'OWNER_NAME',
          placeholder: '请输入车主名称'
        },
        {
          type: 'INPUT',
          label: '车主电话',
          fieldName: 'PHONE',
          placeholder: '请输入车主电话'
        },
        {
          type: 'INPUT',
          label: '车主手机',
          fieldName: 'MOBILE',
          placeholder: '请输入车主手机'
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'CONTACTOR_NAME',
          placeholder: '请输入联系人'
        },
        {
          type: 'INPUT',
          label: '联系人手机',
          fieldName: 'CONTACTOR_MOBILE',
          placeholder: '请输入联系人手机'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'LICENSE',
          placeholder: '请输入车牌号'
        },
        {
          type: 'INPUT',
          label: '底盘号',
          fieldName: 'VIN',
          placeholder: '请输入底盘号'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 140,
        //   fixed: 'left',
        //   render: props => {
        //     return (
        //       <div>
        //       <el-button size="mini" type="text" onClick={() => this.exhale(props.row, '0')}>
        //     智能外呼
        //     </el-button>
        //     <el-button size="mini" type="text" onClick={() => this.exhale(props.row, '00')}>
        //     加0外呼
        //     </el-button>
        //     </div>
        //   );
        //   }
        // },
        {
          title: '车主名称',
          dataIndex: 'OWNER_NAME',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主电话',
          dataIndex: 'PHONE',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主手机',
          dataIndex: 'MOBILE',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '最近进站日期',
          dataIndex: 'CURRENT_MILEAGE_DATE',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '联系人',
          dataIndex: 'CONTACTOR_NAME',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人移动手机',
          dataIndex: 'CONTACTOR_MOBILE',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '购车日期',
          dataIndex: 'SALES_DATE',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        },
        // {
        //   title: '服务顾问',
        //   dataIndex: 'LAST_CONSULTANT_ID',
        //   sorter: true,
        //   disabled: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: []
        // },
        {
          title: '品牌',
          dataIndex: 'BRAND',
          width: 150,
          sorter: true,
          editType: 'select',
          itemList: []
        },
        {
          title: '车系',
          dataIndex: 'SERIES',
          width: 150,
          sorter: true,
          filter: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '车型',
          dataIndex: 'MODEL',
          width: 150,
          sorter: true,
          filter: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '底盘号',
          dataIndex: 'VIN',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '牌照号',
          dataIndex: 'LICENSE',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车龄(天)',
          dataIndex: 'VEHICLE_AGE',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主类别',
          dataIndex: 'OWNER_PROPERTY',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'select',
          render: props => {
            return <span>{props.row.OWNER_PROPERTY ? this.createDictText(props.row.OWNER_PROPERTY, '8011') : ''}</span>;
          }
        },
        {
          title: '进站次数',
          dataIndex: 'HISTORY_REPAIR_TIMES',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    // 搜索
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 显示弹框
    showDia(type) {
      if (this.choose.length === 0) {
        this.$message.error('请选择一条数据');
        return;
      }
      this.chooseVin = this.choose[0].VIN;
      this.chooseLicense = this.choose[0].LICENSE;
      this.chooseOwnerNo = this.choose[0].OWNER_NO;
      switch (type) {
        case 1:
          // 打开提醒录入
          this.selectData = _.cloneDeep(this.choose[0]);
          this.handleType = 'add';
          this.showRemind = true;
          break;
        case 2:
          // 打开提醒记录
          this.showRemindRecord = true;
          break;
        case 3:
          // 打开预约安排
          this.showReservation = true;
          break;
        case 4:
          // 打开维修历史
          this.repairHistoryData = {
            LICENSE: this.choose[0].LICENSE,
            VIN: this.choose[0].VIN,
            ENGINE_NO: this.choose[0].ENGINE_NO,
            OWNER_NAME: this.choose[0].OWNER_NAME
          };
          this.showRepairHistory = true;
          break;
        case 5:
          // 打开建议维修
          this.showRepairSuggest = true;
          break;
        case 6:
          // 打开投诉历史
          this.showComplaintHistory = true;
          break;
      }
    },
    // 取消,关闭弹框
    cancle(type, params) {
      switch (type) {
        case 1:
          // 关闭提醒
          this.showRemind = false;
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
          break;
        case 2:
          // 关闭提醒记录
          this.showRemindRecord = false;
          break;
        case 3:
          // 关闭预约安排
          this.showReservation = false;
          break;
        case 4:
          // 关闭维修历史
          this.showRepairHistory = false;
          break;
        case 5:
          // 关闭建议维修
          this.showRepairSuggest = false;
          break;
        case 6:
          // 关闭投诉历史
          this.showComplaintHistory = false;
          break;
      }
    },
    async getLostRuleInfo() {
      let resData = await getLostRuleInfo();
      this.lostRuleData = resData.data.rows[0];
      this.initForm2(this.lostRuleData);
      this.getEmp();
      this.queryBrand();
      this.querySeries();
      this.queryModel();
    },
    initForm2(lostRuleData) {
      let newStr = [];
      for (let [key, val] of Object.entries(lostRuleData)) {
        let param = {
          fieldName: key,
          value: val
        };
        newStr.push(param);
      }
      this.syncFormListData(newStr);
    },
    // 把返回的数据赋值给表单
    syncFormListData(dataList) {
      const formList = [...this.topFilterList];
      const formFieldNames = formList.map(x => x.fieldName);
      dataList.forEach(x => {
        if (formFieldNames.includes(x.fieldName)) {
          let target = formList.find(k => k.fieldName == x.fieldName);
          if (!target) return;
          target.initialValue = x.value;
        }
      });
    },
    // 获取全部员工
    async getEmp() {
      const res = await getDealerUser(this.editComplaintId);
      let empList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      this.columns.find(item => item.dataIndex === 'LAST_CONSULTANT_ID').editItems = empList; // 上次接待服务顾问
    },
    // 查询所有品牌(供table使用)
    async queryBrand() {
      const res = await getBrand();
      this.columns.find(x => x.dataIndex === 'BRAND').editItems = res.data.map(x => ({ text: x.BRAND_NAME, value: x.BRAND_ID + '' }));
    },
    // 查询所有车系(供table使用)
    async querySeries() {
      const res = await getSeries();
      this.columns.find(x => x.dataIndex === 'SERIES').editItems = res.data.map(x => ({ text: x.SERIES_NAME, value: x.SERIES_ID + '' }));
    },
    // 查询所有车型(供table使用)
    async queryModel() {
      const res = await getModel();
      this.columns.find(x => x.dataIndex === 'MODEL').editItems = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_ID + '' }));
    },
    exhale(val, a) {
      let phone = a + val.MOBILE;
      let userData = {
        userData: {
          ownerNo: val.OWNER_CODE,
          OWNER_CODE: val.OWNER_CODE,
          OWNER_NAME: val.OWNER_NAME,
          date: moment(new Date()).format('YYYY-MM-DD hh:MM:SS')
        }
      };
      if (CallCenter.isLogin()) {
        CallCenter.callout(phone, null, null, null, null, userData);
        this.ownerNo = val.OWNER_CODE;
      } else {
        this.$notify.warning({ title: '提示信息', message: '没有外呼权限!' });
      }
    },
    // 导出
    exportData() {
      this.exportLoading = true;
      LSexport2(this.fetchParams).then(res => {
        exportExcelFile(res, '流失提醒');
        this.exportLoading = false;
      });
    }
  }
};
</script>
